package com.ias.agdis_r.activity;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.db.BoxDBHelper;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.security.endpoint.response.LoginResponse;
import com.ias.agdis_r.util.GPSUtils;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.network.HttpUtil;
import com.ias.agdis_r.util.sdcard.WriteLog;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class LoginActivity extends BaseActivity {

    public static final String EXTRA_EXCEPTION_EXIST_RELOGIN = "com.ias.agdis_exist_0_flag";

    public static final String PREF_USER_NAME = "account_username";
    public static final String PREF_PASSWORD = "account_password";


    private ActionBar actionBar;
    private EditText txt_userno, txt_password;
    private Button loginbtn;

    private boolean flagExist0Relogin = false;
    private boolean flagNeedRetry = false;
    private AlertDialog dialog;

    private PowerManager.WakeLock mWakeLock;
    static Context mContext;

//    private PendingIntent mPendingIntent;
//    private NfcAdapter mNfcAdapter;
//    private IntentFilter[] intentFiltersArray;
    private Handler tryLoginHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            sendLogonInfo(checkForcedLogin());
            if (flagNeedRetry) {
                tryLoginHandler.sendEmptyMessageDelayed(0, 6000);
            }
        }
    };


    //    @Override
//    public void onNewIntent(Intent intent) {
//        // 得到是否检测到ACTION_TECH_DISCOVERED触发
//        super.onNewIntent(intent);
//        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
//            Tag tag = intent.getParcelableExtra(mNfcAdapter.EXTRA_TAG);
//            System.out.println(this.getString(R.string.nfc_tag) + tag);
//            String data = NFCUtil.readTag(tag);
////                NFCUserBean nfcUserBean = new NFCUserBean();
////                nfcUserBean.setUserId("29760");
////                nfcUserBean.setPassword("11111111");
////                String value = gson.toJson(nfcUserBean).toString();
////                System.out.println("#NFC写入：" + value);
////                NFCUtil.writeTag(tag,value);
//
//            NFCUserBean nfcUser = null;
//            try {
//                nfcUser = DataManager.getInstance().getMapper().readValue(data, NFCUserBean.class);
//            } catch (IOException e) {
//                e.printStackTrace();
//                return;
//            }
//            System.out.println(this.getString(R.string.nfc_load_data) + nfcUser.getUserId() + "|" + nfcUser.getPassword());
//            if (S.isNotEmpty(nfcUser.getUserId()) && S.isNotEmpty(nfcUser.getPassword())) {
//                //保存用户名和密码
//                txt_userno.setText(nfcUser.getUserId());
//                txt_password.setText(nfcUser.getPassword());
//                EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.nfc_scan), false);
//                //登录
//                login();
//            }
//        }
//    }

    @Override
    protected void onResume(){
        super.onResume();

//        if (mNfcAdapter != null)
//            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null,
//                    null);
    }
    @Override
    protected void onPause(){
        super.onPause();
//        if (mNfcAdapter != null)
//            mNfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ParameterModel.startLoginActivityFlag = false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ParameterModel.startLoginActivityFlag = true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        actionBar = getActionBar();
        init();
        initActionBarLogin();

        //异常退出再登录

        flagExist0Relogin = getIntent().getBooleanExtra(EXTRA_EXCEPTION_EXIST_RELOGIN, false);
        if (flagExist0Relogin) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

            String username = preferences.getString(PREF_USER_NAME, "");
            String password = preferences.getString(PREF_PASSWORD, "");
            if (S.isNotEmpty(username) && S.isNotEmpty(password)) {
                txt_userno.setText(username);
                txt_password.setText(password);
                tryToLoginUntilSuccessOrBeCancelled();
            }

        }

        mContext = this;
    }

    private void tryToLoginUntilSuccessOrBeCancelled() {

        flagNeedRetry = true;
        this.dialog = new AlertDialog.Builder(this).setTitle(getString(R.string.prompt)).setIcon(android.R.drawable.ic_dialog_info)
                .setMessage(getString(R.string.relogin))
                .setCancelable(false).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        flagNeedRetry = false;
                        tryLoginHandler.removeMessages(0);
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
        tryLoginHandler.sendEmptyMessage(0);
    }

    private void init() {

        txt_userno = (EditText) findViewById(R.id.txt_userno);
        txt_password = (EditText) findViewById(R.id.txt_password);
        loginbtn = (Button) findViewById(R.id.login);
        loginbtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                BoxDBHelper dbHelper = new BoxDBHelper(LoginActivity.this);
                dbHelper.deleteUncheckTTSD();
                dbHelper.closeDB();
                login();
            }
        });

        // 加载上次登录帐号
        String userno = DataBaseManager.getInstance().getSharedString(ParameterModel.T_LAST_USER,
                ParameterModel.LOGIN_ACCOUNT);
        txt_userno.setText(userno);
        txt_userno.requestFocus();

        //mNfcAdapter = mNfcAdapter.getDefaultAdapter(this);
        //mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
        //        getClass()), 0);
    }

    private void login() {


        //读取管理员配置
        String admincount = ".iasadmin";
        try {
            String data = DataBaseManager.getInstance().getString(
                    ParameterModel.T_DONTDELETEME,
                    ParameterModel.T_DONTDELETEME);
            if (S.isNotEmpty(data)) {
                admincount = data;
            }
            Log.i("C_login", "admin:" + admincount);
        } catch (Exception e) {
            Log.w("C_login", "DataBaseManager W: Table:ParameterModel.T_DONTDELETEME, column:ParameterModel.T_DONTDELETEME not found");
        }

        //超级管理员
        if (S.isNotEmpty(admincount) && txt_userno.getText().toString().equals(admincount)
                && txt_password.getText().toString().equals(admincount)) {

            saveAdminData();

            initRefreshBox();
            Intent startIntent = new Intent(this, MainActivity.class);
            startIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            LoginActivity.this.startActivity(startIntent);

        } else {
            String msg = checkInputCharacter();
            if (S.isEmpty(msg)) {
                updateUserPreference();
                sendLogonInfo(checkForcedLogin());
            } else {
                EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
            }
        }


    }

    /**
     * 更新用户信息
     */
    private void updateUserPreference() {
        SharedPreferences pres = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = pres.edit();
        editor.putString(PREF_USER_NAME, txt_userno.getText().toString());
        editor.putString(PREF_PASSWORD, txt_password.getText().toString());
        editor.apply();

    }

    private String checkInputCharacter() {
        String msg = null;
        String password = txt_password.getText().toString();
        if (S.isEmpty(txt_userno.getText().toString())) {
            msg = getString(R.string.inputUsername);
        } else if (S.isEmpty(password)) {
            msg = getString(R.string.inputPassword);
        } else if (password.length() < 8) {
            msg = getString(R.string.password8);
        }
        return msg;
    }

    /**
     * 判断是否是强制登录的账户
     *
     * @return boolean
     * @author zhangsc
     */
    private boolean checkForcedLogin() {
        if (ParameterModel.forcedLoginAccount != null) // 如果强制登录的帐号不为空
        {
            if (ParameterModel.forcedLoginAccount.equals(txt_userno.getText().toString())) // 且强制登录的帐号是当前的帐号
            {
                return true;
            }
        }

        return false;
    }

    /**
     * 给服务器发送登录信息
     */
    private void sendLogonInfo(boolean bflag) {

        String userId = txt_userno.getText().toString();
        String pwd = txt_password.getText().toString();
        String sflag = bflag ? "Y" : "N";
        // TODO 登录
        HttpUtil.getInstance().sendLoginRequeset(userId, pwd, sflag);
        ParameterModel.TOLOGIN_ENB = userId;
    }

    @SuppressLint("InflateParams")
    private void initActionBarLogin() {
        actionBar.setCustomView(LayoutInflater.from(LoginActivity.this).inflate(R.layout.actionbar_settings, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        TextView title = (TextView) findViewById(R.id.txt_title);
        title.setText(R.string.login);
        ImageView back = (ImageView) findViewById(R.id.actionbar_settings_back);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        // TODO Auto-generated method stub

        // 接收到RELI消息
        if (MessageModel.RELI.equals(serviceId)) {
            // 如果登录成功
            if (ServiceManage.getInstance().getIsLogon()) {
                if (this.dialog != null) {
                    dialog.dismiss();
                }
                // 登录成功后，清空保存的强制登录帐号
                ParameterModel.forcedLoginAccount = null;
                tryLoginHandler.removeMessages(0);
                flagNeedRetry = false;
                initRefreshBox();

                PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
                mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TEST");
                if ("L1860".equals(android.os.Build.MODEL)) {
                    AlarmManager mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                    if (null != mAlarmManager) {
                        mAlarmManager.setTimeZone("Asia/Shanghai");// GMT+08:00
                    }
                    Date date = response.getHeader().getCurrentTimestamp();
                    if (null != date) {
                        try {
                            SimpleDateFormat df = new SimpleDateFormat("yy/MM/dd,HH:mm:ss");
                            String nitz = df.format(date);
                            setTime(nitz, SystemClock.elapsedRealtime());
                            WriteLog.getInstance().writeLog("L1860,setTimeSucceed:"+nitz);
                        } catch (Exception e) {
                            WriteLog.getInstance().writeLog("L1860,setTimeException:"+e.getMessage());
                            e.printStackTrace();
                        }
                    }
                }
                Intent startIntent = new Intent(this, MainActivity.class);
                startIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_USERCARBIND.toString())){
                    startIntent.putExtra("AI_T_USERCARBIND", "AI_T_USERCARBIND");
                }
                if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_GPSINFO.toString())) {
                    if (!GPSUtils.isOpen(this)) {
                        startIntent.putExtra("AI_T_GPSINFO", "AI_T_GPSINFO");
                    }
                }
                LoginActivity.this.startActivity(startIntent);
                finish();
            }
        }
    }

    private void initRefreshBox() {
        // TODO Auto-generated method stub
        String enb = JavaBeanManager.getInstance().getUserinfo().getEnb();
        if (enb != null) {
            BoxDBHelper dbHelper = new BoxDBHelper(this);
            int i = dbHelper.getCount(new String[]{enb});
            dbHelper.closeDB();
            DataManager.getInstance().setUnCheckNumber(i);
        }
    }

    @Override
    protected void operateResponseFail(String serviceId, BaseResponse response) {
        // TODO Auto-generated method stub

        // 接收到RELI消息
        if (MessageModel.RELI.equals(serviceId)) {
            String errCode = response.getHeader().getErrorCode();
            if (S.isNotEmpty(errCode) && (errCode.equals("20221") || errCode.equals("20222")))
            // 如果错误代码为20221，20222
            {
                // 记录可强制登录的帐号
                ParameterModel.forcedLoginAccount = ParameterModel.TOLOGIN_ENB;
            }

            // 显示错误消息
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, response.getHeader().getErrorMessage(), false);
        }
    }

    @Override
    protected void updateUI(String tag) {
        // TODO Auto-generated method stub

    }

    /**
     * 保存数据到本地数据库T_USERINFO表中
     */
    private void saveAdminData() {

        UserInfoBean infoBean = new UserInfoBean();

        infoBean.setEnb("");
        infoBean.setEnm("admin");
        infoBean.setRli("");
        infoBean.setRln("admin");
        infoBean.setPwd(S.valueOf(txt_password.getText().toString()));

        infoBean.setIsadmin(true);

        JavaBeanManager.getInstance().saveUserLoginData(infoBean);
        ServiceManage.getInstance().setLogon(true);
    }

    private void setTime(String nitz, long nitzReceiveTime) {
        try {
            Calendar c = Calendar.getInstance();
            c.clear();
            c.set(Calendar.DST_OFFSET, 0);
            String[] nitzSubs = nitz.split("[/:,+-]");
            int year = 2000 + Integer.parseInt(nitzSubs[0]);
            c.set(Calendar.YEAR, year);
            // month is 0 based!
            int month = Integer.parseInt(nitzSubs[1]) - 1;
            c.set(Calendar.MONTH, month);
            int date = Integer.parseInt(nitzSubs[2]);
            c.set(Calendar.DATE, date);
            int hour = Integer.parseInt(nitzSubs[3]);
            c.set(Calendar.HOUR_OF_DAY, hour);
            int minute = Integer.parseInt(nitzSubs[4]);
            c.set(Calendar.MINUTE, minute);
            int second = Integer.parseInt(nitzSubs[5]);
            c.set(Calendar.SECOND, second);
            boolean sign = (nitz.indexOf('-') == -1);
            int tzOffset = (nitzSubs.length >= 7) ? Integer.parseInt(nitzSubs[6]) : 0;
            int dst = (nitzSubs.length >= 8) ? Integer.parseInt(nitzSubs[7]) : 0;
            tzOffset = (sign ? 1 : -1) * tzOffset * 15 * 60 * 1000;
            TimeZone zone = null;
            if (nitzSubs.length >= 9) {
                String tzname = nitzSubs[8].replace('!', '/');
                zone = TimeZone.getTimeZone(tzname);
            }
            if (zone == null) {
                //zone = getNitzTimeZone(tzOffset, (dst != 0), c.getTimeInMillis());
            }
            try {
                mWakeLock.acquire();
                long millisSinceNitzReceived = SystemClock.elapsedRealtime() - nitzReceiveTime;
                if (millisSinceNitzReceived < 0) {
                    Log.w("ApkInterfaceReceiver", "return 1£º" + millisSinceNitzReceived);
                    return;
                }
                if (millisSinceNitzReceived > Integer.MAX_VALUE) {
                    Log.w("ApkInterfaceReceiver", "return 2£º" + millisSinceNitzReceived);
                    return;
                }
                c.add(Calendar.MILLISECOND, (int) millisSinceNitzReceived);
                if (zone == null)
                    setAndBroadcastNetworkSetTime(c.getTimeInMillis(), null);
                else
                    setAndBroadcastNetworkSetTime(c.getTimeInMillis(), zone.getID());
            } finally {
                mWakeLock.release();
            }
        } catch (RuntimeException ex) {
            Log.w("TEST", "ex £º" + ex);
        }
    }

    private void setAndBroadcastNetworkSetTime(long time,String zoneId) {
        Intent intent = new Intent("android.intent.action.ACTION_THIRDAPP_TIME_SYC");
        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
        intent.putExtra("settime", time);
        intent.putExtra("curtime", SystemClock.elapsedRealtime());
        if (zoneId != null)
            intent.putExtra("zone", zoneId);
        mContext.sendBroadcast(intent);
    }

    private TimeZone getNitzTimeZone(int offset, boolean dst, long when) {
        TimeZone guess = findTimeZone(offset, dst, when);
        if (guess == null) {
            guess = findTimeZone(offset, !dst, when);
        }
        return guess;
    }

    private TimeZone findTimeZone(int offset, boolean dst, long when) {
        int rawOffset = offset;
        if (dst) {
            rawOffset -= 3600000;
        }
        String[] zones = TimeZone.getAvailableIDs(rawOffset);
        TimeZone guess = null;
        Date d = new Date(when);
        for (String zone : zones) {
            TimeZone tz = TimeZone.getTimeZone(zone);
            if (tz.getOffset(when) == offset &&
                    tz.inDaylightTime(d) == dst) {
                guess = tz;
                break;
            }
        }
        return guess;
    }
}


